package cn.zero.letaomallspringboot.controller;

import cn.zero.letaomallspringboot.Constant.ResultCode;
import cn.zero.letaomallspringboot.common.PageResult;
import cn.zero.letaomallspringboot.common.Result;
import cn.zero.letaomallspringboot.entity.RefundRecord;
import cn.zero.letaomallspringboot.service.IRefundRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "退款记录管理", description = "退款记录的查询、创建、更新、删除等操作")
@RestController
@RequestMapping("/refundRecord")
public class RefundController {
    private final IRefundRecordService refundRecordService;
    private static final Logger logger = LoggerFactory.getLogger(RefundController.class);

    public RefundController(IRefundRecordService refundRecordService) {
        this.refundRecordService = refundRecordService;
    }

    /**
     * 分页查询退款记录列表
     */
    @Operation(summary = "分页查询退款记录列表", description = "支持按退款单号、用户ID、订单ID、退款原因、处理状态筛选")
    @GetMapping("/list")
    public Result<PageResult<RefundRecord>> refundRecordList(
            @Parameter(description = "页码（默认1）", required = false, example = "1")
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页条数（默认10）", required = false, example = "10")
            @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "退款单号（模糊查询）", required = false)
            @RequestParam(required = false) String refundNumber,
            @Parameter(description = "用户ID", required = false)
            @RequestParam(required = false) Integer userId,
            @Parameter(description = "订单ID", required = false)
            @RequestParam(required = false) Integer orderId,
            @Parameter(description = "退款原因", required = false)
            @RequestParam(required = false) String refundReason,
            @Parameter(description = "处理状态（已退款/处理中）", required = false)
            @RequestParam(required = false) String processStatus) {

        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("size", size);

        if (refundNumber != null && !refundNumber.trim().isEmpty()) {
            params.put("refundNumber", refundNumber.trim());
        }
        if (userId != null) {
            params.put("userId", userId);
        }
        if (orderId != null) {
            params.put("orderId", orderId);
        }
        if (refundReason != null && !refundReason.trim().isEmpty()) {
            params.put("refundReason", refundReason.trim());
        }
        if (processStatus != null && !processStatus.trim().isEmpty()) {
            params.put("processStatus", processStatus.trim());
        }

        PageResult<RefundRecord> pageResult = refundRecordService.refundRecordList(params);
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询退款记录详情
     */
    @GetMapping("/{id}")
    public Result<RefundRecord> getRefundRecord(@PathVariable Integer id) {
        logger.info("查询退款记录详情: {}", id);
        RefundRecord refundRecord = refundRecordService.getRefundRecordById(id);
        if (refundRecord == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 可根据实际情况定义退款记录不存在的枚举
        }
        return Result.success(refundRecord);
    }


    /**
     * 更新退款记录信息
     */
    @PutMapping("/{id}")
    public Result<RefundRecord> updateRefundRecord(@PathVariable Integer id, @RequestBody RefundRecord refundRecord) {
        logger.info("更新退款记录: {},{}", id, refundRecord);

        // 验证退款记录是否存在
        RefundRecord existingRefundRecord = refundRecordService.getRefundRecordById(id);
        if (existingRefundRecord == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 可根据实际情况定义退款记录不存在的枚举
        }

        refundRecord.setId(id); // 设置ID以确保更新正确记录
        boolean success = refundRecordService.updateRefundRecord(refundRecord);
        if (!success) {
            return Result.fail(ResultCode.CUSTOM_ERROR, "退款记录更新失败"); // 可根据实际情况定义退款记录更新失败的枚举
        }
        return Result.success(refundRecord, "退款记录更新成功");
    }

    /**
     * 根据ID删除退款记录
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteRefundRecord(@PathVariable Integer id) {
        logger.info("删除退款记录: {}", id);

        RefundRecord refundRecord = refundRecordService.getRefundRecordById(id);
        if (refundRecord == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 可根据实际情况定义退款记录不存在的枚举
        }

        boolean success = refundRecordService.deleteRefundRecord(id);
        if (!success) {
            return Result.fail(ResultCode.CUSTOM_ERROR, "退款记录删除失败"); // 可根据实际情况定义退款记录删除失败的枚举
        }
        return Result.success(null, "退款记录删除成功");
    }

    /**
     * 批量删除退款记录
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteRefundRecord(@RequestBody List<Integer> ids) {
        logger.info("批量删除退款记录: {}", ids);

        if (ids == null || ids.isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "请选择要删除的退款记录");
        }

        boolean success = refundRecordService.batchDeleteRefundRecord(ids);
        if (!success) {
            return Result.fail(ResultCode.CUSTOM_ERROR, "退款记录批量删除失败"); // 可根据实际情况定义退款记录批量删除失败的枚举
        }
        return Result.success(null, "退款记录批量删除成功");
    }

    /**
     * 更新退款记录处理状态
     */
    @PatchMapping("/{id}/status")
    public Result<RefundRecord> updateRefundRecordStatus(
            @PathVariable Integer id,
            @RequestParam String processStatus) {
        logger.info("更新退款记录处理状态: {} -> {}", id, processStatus);

        RefundRecord refundRecord = refundRecordService.getRefundRecordById(id);
        if (refundRecord == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 可根据实际情况定义退款记录不存在的枚举
        }

        boolean success = refundRecordService.updateRefundRecordStatus(id, processStatus);
        if (!success) {
            return Result.fail(ResultCode.CUSTOM_ERROR, "退款记录处理状态更新失败"); // 可根据实际情况定义退款记录处理状态更新失败的枚举
        }

        refundRecord.setProcessStatus(processStatus);
        return Result.success(refundRecord, "退款记录处理状态更新成功");
    }
}